using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace MuYue.Common
{
    public static class Utility
    {
        public static string ToXmlString(string inputString) {
            if (string.IsNullOrWhiteSpace(inputString)) {
                throw new ArgumentNullException("网络文本转换为XML文本失败");
            }
            int num = inputString.IndexOf("<?xml", StringComparison.OrdinalIgnoreCase);
            int num2 = inputString.LastIndexOf(">");
            if (num >= 0 && num2 > num) {
                return inputString.Substring(num, num2 - num + 1);
            }
            throw new Exception("XML对等解析失败");
        }
        public static string Md5Encoding(string str) {
            return Utility.Md5Encoding(Encoding.UTF8.GetBytes(str));
        }
        public static string Md5Encoding(byte[] buffer) {
            string result;
            using (MD5 mD = MD5.Create()) {
                result = Utility.ConverHashToString(mD.ComputeHash(buffer));
            }
            return result;
        }
        public static string Md5EncodingFile(string fileName) {
            if (string.IsNullOrWhiteSpace(fileName)) {
                throw new ArgumentNullException("fileName");
            }
            if (!File.Exists(fileName)) {
                throw new Exception("文件不存在");
            }
            string result;
            using (FileStream fileStream = File.OpenRead(fileName)) {
                result = Utility.Md5Encoding(fileStream);
            }
            return result;
        }
        public static string Md5Encoding(Stream fs) {
            string result;
            using (MD5 mD = MD5.Create()) {
                byte[] hs = mD.ComputeHash(fs);
                result = Utility.ConverHashToString(hs);
            }
            return result;
        }
        private static string ConverHashToString(IEnumerable<byte> hs) {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (byte current in hs) {
                stringBuilder.Append(current.ToString("x2"));
            }
            return stringBuilder.ToString();
        }
        public static void CreateDirectoryByFileName(string fileName) {
            string directoryName = Path.GetDirectoryName(fileName);
            if (!Directory.Exists(directoryName)) {
                Directory.CreateDirectory(directoryName);
            }
        }


        public static int GetWeek(DateTime time) {
            var tmp = DateTime.Now;
            while (tmp.DayOfWeek != DayOfWeek.Monday) {
                tmp = tmp.AddDays(1);
            }
            return time.AddDays(-1 * (tmp.DayOfYear % 7)).DayOfYear / 7;
        }

    }
}
